package service;

import java.util.List;

import bean.WechatCache;
import dao.WechatCacheDAOImpl;

public class WechatCacheService {

    private WechatCacheDAOImpl wechatCacheDAOImpl;
    
    public void setWechatCacheDAOImpl(WechatCacheDAOImpl wechatCacheDAOImpl) {
        this.wechatCacheDAOImpl = wechatCacheDAOImpl;
    }

    /**
     * Get last cache from database
     * @return
     */
    public WechatCache getLast() {
        List<WechatCache> list = wechatCacheDAOImpl.findLast();
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    /**
     * Add or update access token
     * @param cache
     */
    public void saveOrUpdateAccessToken(WechatCache cache) {
        if (cache == null || cache.getAccessToken() == null || cache.getAccessTokenExpires() == null) {
            return;
        }
        
        WechatCache last = getLast();
        if (last == null) {
            wechatCacheDAOImpl.save(cache);
        } else {
            last.setAccessToken(cache.getAccessToken());
            last.setAccessTokenExpires(cache.getAccessTokenExpires());
            wechatCacheDAOImpl.merge(last);
        }
    }

    /**
     * Add or update jsapi ticket
     * @param cache
     */
    public void saveOrUpdateJsapiTicket(WechatCache cache) {
        if (cache == null || cache.getJsapiTicket() == null || cache.getJsapiTicketExpires() == null) {
            return;
        }
        
        WechatCache last = getLast();
        if (last == null) {
            wechatCacheDAOImpl.save(cache);
        } else {
            last.setJsapiTicket(cache.getJsapiTicket());
            last.setJsapiTicketExpires(cache.getJsapiTicketExpires());
            wechatCacheDAOImpl.merge(last);
        }
    }

    /**
     * Add or update api ticket
     * @param cache
     */
    public void saveOrUpdateApiTicket(WechatCache cache) {
        if (cache == null || cache.getApiTicket() == null || cache.getApiTicketExpires() == null) {
            return;
        }
        
        WechatCache last = getLast();
        if (last == null) {
            wechatCacheDAOImpl.save(cache);
        } else {
            last.setApiTicket(cache.getApiTicket());
            last.setApiTicketExpires(cache.getApiTicketExpires());
            wechatCacheDAOImpl.merge(last);
        }
    }
    
}
